package com.kzd.sdk.core;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Process;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.kzd.sdk.callback.KZD_OnHideListener;
import com.kzd.sdk.callback.KZD_OnLoginListener;
import com.kzd.sdk.callback.KZD_OnPayListener;
import com.kzd.sdk.callback.KZD_OnRoleListener;
import com.kzd.sdk.callback.KZD_OnSdkListener;
import com.kzd.sdk.entity.KZD_LoginMain;
import com.kzd.sdk.entity.KZD_LoginSmall;
import com.kzd.sdk.entity.KZD_SdkInitParams;
import com.kzd.sdk.entity.KZD_SdkPayParams;
import com.kzd.sdk.entity.KZD_SdkRoleParams;
import com.kzd.sdk.entity.KZD_UserInfo;
import com.kzd.sdk.ui.activity.KZD_AccessActivity;
import com.kzd.sdk.ui.widget.KZD_FloatView;
import com.kzd.sdk.utils.SPUtils;
import com.lzy.okgo.OkGo;

import java.lang.ref.WeakReference;

import static com.kzd.sdk.core.KZD_ApiConstance.GT_ACTIVITY_REQUEST_CODE;
import static com.kzd.sdk.core.KZD_ApiConstance.GT_ACTIVITY_RESULT_CODE;
import static com.kzd.sdk.core.KZD_ApiConstance.SP_LOGIN_MAIN;
import static com.kzd.sdk.core.KZD_ApiConstance.SP_LOGIN_SMALL;
import static com.kzd.sdk.core.KZD_ApiConstance.SP_USER_INFO;

public final class KZD_SdkController implements KZD_OnSdkListener, KZD_OnHideListener {

    private static WeakReference<Context> mContextWeakReference;

    private static WeakReference<Activity> mActivityWeakReference;

    private static WeakReference<KZD_FloatView> mFloatViewWeakReference;

    private static SPUtils mSpUtils;

    private static KZD_SdkInitParams mSdkInitParams;

    private static KZD_OnLoginListener mOnLoginListener;

    private static KZD_OnPayListener mOnPayListener;

    private static KZD_OnRoleListener mOnRoleListener;

    private static KZD_OnHideListener mOnHideListener;

    @Override
    public void init(Application application, KZD_SdkInitParams params) {
        setContextWeakReference(application.getApplicationContext());
        setSdkInitParams(params);
        setSp(application.getApplicationContext());
        OkGo.getInstance().init(application);
        setOnHideListener(this);
    }

    @Override
    public void login(Activity activity, KZD_OnLoginListener loginListener) {
        setActivityWeakReference(activity);
        if (loginListener != null) {
            setOnLoginListener(loginListener);
        }
        //跳转登录页面
        KZD_AccessActivity.open();
    }

    @Override
    public void paying(Activity activity, KZD_SdkPayParams payParams, KZD_OnPayListener payListener) {
        setActivityWeakReference(activity);
        if (payListener != null) {
            setOnPayListener(payListener);
        }
        //跳转支付页面
        KZD_AccessActivity.openPay(payParams);
    }

    @Override
    public void roles(Activity activity, KZD_SdkRoleParams roleParams, KZD_OnRoleListener rolesListener) {
        setActivityWeakReference(activity);
        if (rolesListener != null) {
            setOnRolesListener(rolesListener);
        }
        //上传角色信息
        KZD_AccessActivity.openRole(roleParams);
    }

    @Override
    public void onCreate(Activity activity) {
        setActivityWeakReference(activity);
    }

    @Override
    public void onStart(Activity activity) {
        setActivityWeakReference(activity);
    }

    @Override
    public void onResume(Activity activity) {
        setActivityWeakReference(activity);
    }

    @Override
    public void onPause(Activity activity) {
        setActivityWeakReference(activity);
    }

    @Override
    public void onStop(Activity activity) {
        setActivityWeakReference(activity);
    }

    @Override
    public void onRestart(Activity activity) {
        setActivityWeakReference(activity);
    }

    @Override
    public void onDestroy(Activity activity) {
        setActivityWeakReference(activity);
        closeFloatView();
        clearLoginSmall();
        clearActivityWeakReference();
    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        setActivityWeakReference(activity);
        if (requestCode == GT_ACTIVITY_REQUEST_CODE && resultCode == GT_ACTIVITY_RESULT_CODE) {
            openFloatView();
        }
    }

    @Override
    public void openFloatView(Activity activity) {
        setActivityWeakReference(activity);
        openFloatView();
    }

    @Override
    public void closeFloatView(Activity activity) {
        setActivityWeakReference(activity);
        closeFloatView();
    }

    @Override
    public void exit(Activity activity) {
        AlertDialog dialog = new AlertDialog.Builder(activity).create();
        dialog.setTitle("您确定要退出游戏吗？");
        dialog.setButton(-1, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                onDestroy(activity);
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Process.killProcess(Process.myPid());
            }
        });
        dialog.setButton(-2, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    public void onAccountSwitch() {
        closeFloatView();
        clearUserInfo();
        clearLoginSmall();
        clearLoginMain();
    }

    /**
     * 是否初始化SDK
     *
     * @return true未初始化 false已初始化
     */
    protected boolean isNotInit() {
        return getContext() == null && getSdkInitParams() == null;
    }

    /**
     * 主号和小号是否同时登录
     *
     * @return true未登录 false已登录
     */
    protected boolean isNotLogin() {
        return isNotLoginMain() || isNotLoginSmall();
    }


    /**
     * 主账号是否登录
     *
     * @return true未登录 false已登录
     */
    public static boolean isNotLoginMain() {
        return getLoginMain() == null || getUserInfo() == null;
    }

    /**
     * 小号是否登录
     *
     * @return true未登录 false已登录
     */
    public static boolean isNotLoginSmall() {
        return getLoginSmall() == null;
    }


    /**
     * 获取主号登录信息
     *
     * @return 返回主号登录信息
     */
    public static KZD_LoginMain getLoginMain() {
        String loginMainJson = getSp().getString(SP_LOGIN_MAIN);
        try {
            return new Gson().fromJson(loginMainJson, KZD_LoginMain.class);
        } catch (JsonIOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 清除主号登录信息
     */
    private void clearLoginMain() {
        getSp().remove(SP_LOGIN_MAIN);
    }

    /**
     * 获取小号登录信息
     *
     * @return 返回小号登录信息
     */
    public static KZD_LoginSmall getLoginSmall() {
        String loginSmallJson = getSp().getString(SP_LOGIN_SMALL);
        try {
            return new Gson().fromJson(loginSmallJson, KZD_LoginSmall.class);
        } catch (JsonIOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 清除小号信息数据
     */
    private void clearLoginSmall() {
        getSp().remove(SP_LOGIN_SMALL);
    }

    /**
     * 获取用户信息
     *
     * @return 返回用户信息
     */
    public static KZD_UserInfo getUserInfo() {
        String userInfoJson = getSp().getString(SP_USER_INFO);
        try {
            return new Gson().fromJson(userInfoJson, KZD_UserInfo.class);
        } catch (JsonIOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 清除用户信息
     */
    private void clearUserInfo() {
        getSp().remove(SP_USER_INFO);
    }


    /**
     * 打开悬浮窗
     */
    private void openFloatView() {
        if (isNotLogin()) {
            return;
        }
        if (getFloatView() == null) {
            setFloatViewWeakReference(getActivity());
        }
        getFloatView().openFloatView();
    }

    /**
     * 关闭悬浮窗
     */
    private void closeFloatView() {
        if (getFloatView() == null) {
            return;
        }
        getFloatView().closeFloatView();
        clearFloatViewWeakReference();
    }

    /**
     * 获取推广员id
     */
    public static String getGTMemberId() {
        if (getContext() == null) {
            return null;
        }
        Uri uri = Uri.parse("content://" + KZD_ApiConstance.GT_GAME_PACKAGE + ".provider/GameMember");
        @SuppressLint("Recycle")
        Cursor cursor = getContext().getContentResolver().query(uri, (null), (null), (null), (null));
        String memberId = null;
        while (cursor.moveToNext()) {
            int index = cursor.getColumnIndex("member");
            memberId = cursor.getString(index);
        }
        return memberId;
    }

    /**
     * 获取Application上下文
     *
     * @return context
     */
    public static Context getContext() {
        if (mContextWeakReference != null) {
            return mContextWeakReference.get();
        }
        return null;
    }

    /**
     * 设置Application上下文,在init()中初始化
     *
     * @param context 上下文
     */
    private void setContextWeakReference(Context context) {
        if (mContextWeakReference != null) {
            mContextWeakReference.clear();
        }
        mContextWeakReference = new WeakReference<>(context);
    }

    /**
     * 清除Context弱引用
     */
    private void clearContextWeakReference() {
        if (mContextWeakReference == null) {
            return;
        }
        mContextWeakReference.clear();
        mContextWeakReference = null;
    }

    /**
     * 获取Activity活动
     *
     * @return activity
     */
    public static Activity getActivity() {
        if (mActivityWeakReference != null) {
            return mActivityWeakReference.get();
        }
        return null;
    }


    /**
     * 设置Activity活动,随生命周期设置
     *
     * @param activity 活动
     */
    private void setActivityWeakReference(Activity activity) {
        if (mActivityWeakReference != null) {
            mActivityWeakReference.clear();
        }
        mActivityWeakReference = new WeakReference<>(activity);
    }

    /**
     * 清除Activity弱引用
     */
    private void clearActivityWeakReference() {
        if (mActivityWeakReference == null) {
            return;
        }
        mActivityWeakReference.clear();
        mActivityWeakReference = null;
    }

    /**
     * 获取悬浮窗视图
     *
     * @return floatView
     */
    public static KZD_FloatView getFloatView() {
        if (mFloatViewWeakReference != null) {
            return mFloatViewWeakReference.get();
        }
        return null;
    }

    /**
     * 初始化悬浮窗视图
     *
     * @param activity 活动
     */
    private void setFloatViewWeakReference(Activity activity) {
        if (mFloatViewWeakReference != null) {
            mFloatViewWeakReference.clear();
        }
        mFloatViewWeakReference = new WeakReference<>(new KZD_FloatView(activity));
    }

    /**
     * 清除FloatView弱引用
     */
    private void clearFloatViewWeakReference() {
        if (mFloatViewWeakReference == null) {
            return;
        }
        mFloatViewWeakReference.clear();
        mFloatViewWeakReference = null;
    }

    /**
     * 初始化SharedPreferences对象
     *
     * @param context 上下文
     */
    private void setSp(Context context) {
        mSpUtils = SPUtils.getInstance(context);
        mSpUtils.remove(SP_LOGIN_SMALL);
    }

    /**
     * 获取SharedPreferences对象
     *
     * @return SharedPreferences
     */
    public static SPUtils getSp() {
        return mSpUtils;
    }

    public static KZD_SdkInitParams getSdkInitParams() {
        return mSdkInitParams;
    }

    private void setSdkInitParams(KZD_SdkInitParams sdkInitParams) {
        mSdkInitParams = sdkInitParams;
    }

    public static KZD_OnLoginListener getOnLoginListener() {
        return mOnLoginListener;
    }

    public void setOnLoginListener(KZD_OnLoginListener onLoginListener) {
        mOnLoginListener = onLoginListener;
    }

    public boolean isNotLoginListener() {
        return getOnLoginListener() == null;
    }

    public static KZD_OnPayListener getOnPayListener() {
        return mOnPayListener;
    }

    public void setOnPayListener(KZD_OnPayListener onPayListener) {
        mOnPayListener = onPayListener;
    }

    public boolean isNotPayListener() {
        return mOnPayListener == null;
    }

    public static KZD_OnRoleListener getOnRolesListener() {
        return mOnRoleListener;
    }

    public void setOnRolesListener(KZD_OnRoleListener onRoleListener) {
        mOnRoleListener = onRoleListener;
    }

    public boolean isNotRolesListener() {
        return mOnRoleListener == null;
    }

    public static KZD_OnHideListener getOnHideListener() {
        return mOnHideListener;
    }

    private void setOnHideListener(KZD_OnHideListener onHideListener) {
        mOnHideListener = onHideListener;
    }
}
